package net.ksic.uridongne;

import java.util.ArrayList;
import java.util.List;

import net.ksic.common.NetworkManager;
import net.ksic.common.PreferenceManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class GroupActivity extends Activity implements OnClickListener{
	
	Button home = null, takepic = null, album = null, clist = null, group = null;
	
	ListView lv1 = null;
	ArrayList<GroupItem> groupList = null;
	JSONArray contacts = null;
	DataAdapter adapter = null;
		
	String send_message = null, address = null, strJSON = null;
	
	PreferenceManager preferenceManager;
	NetworkManager networkManager;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_group);
		
		Intent fromIntent = getIntent();
		send_message = fromIntent.getStringExtra("SEND_MESSAGE");
		address = fromIntent.getStringExtra("ADDRESS");
		
		networkManager = new NetworkManager();
		preferenceManager = new PreferenceManager(getApplicationContext());
		
		setButton();
	}	
	
	public void setButton() {
		home = (Button) findViewById(R.id.home);
		takepic = (Button) findViewById(R.id.takepic);
		album = (Button) findViewById(R.id.album);
		clist = (Button) findViewById(R.id.clist);
		group = (Button) findViewById(R.id.group);
		
		lv1 = (ListView) findViewById(R.id.listView2);
		groupList = new ArrayList<GroupItem>();
		adapter = new DataAdapter(this, groupList);
		lv1.setAdapter(adapter);

		home.setOnClickListener(this);
		takepic.setOnClickListener(this);
		album.setOnClickListener(this);
		clist.setOnClickListener(this);
		group.setOnClickListener(this);

		Log.i("버튼셋업", "완료");
		
		// 비동기처리 구동
		new ListWorker().execute();
	}
	
	public class ListWorker extends AsyncTask<Object, ContentsItem, Object> {

		/** 작업이 진행되기 시작할 시점에, 화면단의 처리를 구현한다. -> 로딩표시 */
		@Override
		protected void onPreExecute() {

		}

		/**
		 * 실질적인 데이터 처리 작업을 진행 -> 통신과 Xml 파싱 작업 주의) 컴포넌트 객체나 Adapter에 접근하지 못한다.
		 * -> 에러표시는 없음.
		 */
		@Override
		protected Object doInBackground(Object... params) {

			String URL = "http://20.20.20.124:8080/MyServer/json_group.html";

			strJSON = networkManager.getJSP(URL);

			Log.i("json", strJSON);	
			
			publishProgress();

			return null;
		}

		/**
		 * doInBackground의 중간 결과를 화면에 반영한다. doInBackground에서 publishProgress()를
		 * 호출하면 여기가 실행된다. -> adapter.add(.....);
		 */
		@Override
		protected void onProgressUpdate(ContentsItem... param) {
			if (strJSON != null) {
				try {
					JSONObject jsonObj = new JSONObject(strJSON);

					// Getting JSON Array node
					contacts = jsonObj.getJSONArray("group");

					// looping through All Contacts
					for (int i = 0; i < contacts.length(); i++) {
						JSONObject c = contacts.getJSONObject(i);

						String groupcd = c.getString("groupcd");
						String groupname = c.getString("groupname");
						String groupsubject = c.getString("groupsubject");
						String content = c.getString("content");
						String stdate = c.getString("stdate");
						String modate = c.getString("modate");						
						
						adapter.add(new GroupItem(groupcd, groupname, groupsubject, content, stdate, modate));	
						
						Log.i("adapter.add", groupcd);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}
		}

		/**
		 * doInBackground가 온전히 return 되었을 경우 실행된다. 작업 종료 후의 화면 처리를 수행하는 목적 ->
		 * 로딩바 닫기
		 */
		@Override
		protected void onPostExecute(Object param) {

		}

		/**
		 * doInBackgorund에서 cancel(true) 메서드를 호출하면 실행된다. 작업 실패에 대한 메시지 표시 용도
		 */
		@Override
		protected void onCancelled() {

		}
	}
	
	public class DataAdapter extends ArrayAdapter<GroupItem> {
		private LayoutInflater inflater = null;

		public DataAdapter(Context context, List<GroupItem> objects) {
			super(context, 0, objects);
			inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view = null;

			if (convertView == null) {
				view = inflater.inflate(R.layout.list_group, null);
			} else {
				view = convertView;
			}

			final GroupItem item = getItem(position);

			if (item != null) {
				//Log.i("item", item.getComment());
				Log.i("item", "" + item.getGroupname());

				TextView tv1 = (TextView) view.findViewById(R.id.textView1);
				tv1.setText("" + item.getGroupname());

				TextView tv2 = (TextView) view.findViewById(R.id.textView2);
				tv2.setText(item.getGroupsubject());
			}
			Log.i("DataAdapter", "3");
			return view;
		}
	}

	@Override
	public void onClick(View v) {
		String sendMsg = "";

		Intent intent = null;

		switch (v.getId()) {
		case R.id.home:
			sendMsg = "map";
			Toast.makeText(this, "첫화면", Toast.LENGTH_SHORT).show();
			intent = new Intent(this, MapActivity.class);
			break;
		case R.id.takepic:
			sendMsg = "camera";
			Toast.makeText(this, "카메라", Toast.LENGTH_SHORT).show();
			intent = new Intent(this, PicActivity.class);
			break;
		case R.id.album:
			sendMsg = "album";
			Toast.makeText(this, "앨범", Toast.LENGTH_SHORT).show();
			intent = new Intent(this, PicActivity.class);
			break;
		case R.id.clist:
			sendMsg = "clist";
			Toast.makeText(this, "컨텐츠", Toast.LENGTH_SHORT).show();
			intent = new Intent(this, ContentsActivity.class);
			break;
		case R.id.group:
			sendMsg = "group";
			Toast.makeText(this, "커뮤니티", Toast.LENGTH_SHORT).show();
			intent = new Intent(this, GroupActivity.class);
			break;
		}

		intent.putExtra("SEND_MESSAGE", sendMsg);
		intent.putExtra("ADDRESS", address);

		startActivity(intent);
	}
}